package com.example.cm_player.manager

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.os.Build
import android.util.Log
import com.example.cm_utils.ContextHelper

/**
 * 音频焦点管理器
 * 负责管理应用的音频焦点，确保与其他音频应用的协调播放
 */
class AudioFocusManager private constructor() : AudioManager.OnAudioFocusChangeListener {
    
    companion object {
        private const val TAG = "AudioFocusManager"

        @Volatile
        private var instance: AudioFocusManager? = null
        
        fun getInstance(): AudioFocusManager {
            return instance ?: synchronized(this) {
                instance ?: AudioFocusManager().also { instance = it }
            }
        }
    }
    
    private var audioManager: AudioManager? = null
    private var audioFocusRequest: AudioFocusRequest? = null
    private var hasAudioFocus = false
    
    // 音频焦点变化回调接口
    interface AudioFocusChangeListener {
        fun onAudioFocusGained()
        fun onAudioFocusLost()
        fun onAudioFocusLostTransient()
        fun onAudioFocusLostTransientCanDuck()
    }
    
    private var focusChangeListener: AudioFocusChangeListener? = null
    
    /**
     * 设置音频焦点变化监听器
     */
    fun setAudioFocusChangeListener(listener: AudioFocusChangeListener) {
        this.focusChangeListener = listener
    }
    
    /**
     * 初始化音频管理器
     */
    fun init() {
        val context = ContextHelper.context?.get()
        if (context != null) {
            audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        }
        Log.v(TAG,"AudioFocusManager init")
    }
    
    /**
     * 请求音频焦点
     */
    fun requestAudioFocus(): Boolean {
        if (audioManager == null || hasAudioFocus) return hasAudioFocus
        
        val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            requestAudioFocusOreo()
        } else {
            requestAudioFocusLegacy()
        }
        
        hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
        return hasAudioFocus
    }
    
    @Suppress("DEPRECATION")
    private fun requestAudioFocusOreo(): Int {
        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
        
        audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
            .setAudioAttributes(audioAttributes)
            .setAcceptsDelayedFocusGain(true)
            .setOnAudioFocusChangeListener(this)
            .build()
        
        return audioManager!!.requestAudioFocus(audioFocusRequest!!)
    }
    
    @Suppress("DEPRECATION")
    private fun requestAudioFocusLegacy(): Int {
        return audioManager!!.requestAudioFocus(
            this,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN
        )
    }
    
    /**
     * 释放音频焦点
     */
    fun abandonAudioFocus() {
        if (audioManager == null || !hasAudioFocus) return
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            audioManager!!.abandonAudioFocusRequest(audioFocusRequest!!)
        } else {
            @Suppress("DEPRECATION")
            audioManager!!.abandonAudioFocus(this)
        }
        
        hasAudioFocus = false
        audioFocusRequest = null
    }
    
    /**
     * 检查是否拥有音频焦点
     */
    fun hasAudioFocus(): Boolean = hasAudioFocus
    
    /**
     * 音频焦点变化回调
     */
    override fun onAudioFocusChange(focusChange: Int) {
        when (focusChange) {
            AudioManager.AUDIOFOCUS_GAIN -> {
                Log.v(TAG,"AudioFocusManager onAudioFocusChange AUDIOFOCUS_GAIN")
                hasAudioFocus = true
                focusChangeListener?.onAudioFocusGained()
            }
            AudioManager.AUDIOFOCUS_LOSS -> {
                Log.v(TAG,"AudioFocusManager onAudioFocusChange AUDIOFOCUS_LOSS")
                hasAudioFocus = false
                focusChangeListener?.onAudioFocusLost()
            }
            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                Log.v(TAG,"AudioFocusManager onAudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT")
                hasAudioFocus = false
                focusChangeListener?.onAudioFocusLostTransient()
            }
            AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
                Log.v(TAG,"AudioFocusManager onAudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK")
                hasAudioFocus = false
                focusChangeListener?.onAudioFocusLostTransientCanDuck()
            }
        }
    }
    
    /**
     * 释放资源
     */
    fun release() {
        Log.v(TAG,"AudioFocusManager release")
        abandonAudioFocus()
        focusChangeListener = null
        audioManager = null
        audioFocusRequest = null
    }
}